<template>
    <div class="app-container">
      <!-- 搜索表单 -->
      <div class="search-wrapper">
        <el-form ref="queryFormRef" :model="queryParams" :inline="true">
          <el-form-item label="标题" prop="title">
            <el-input
              v-model="queryParams.title"
              placeholder="请输入文章标题"
              clearable
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item label="分类" prop="categoryId">
            <el-select v-model="queryParams.categoryId" placeholder="请选择分类" clearable>
              <el-option
                v-for="item in categoryOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="标签" prop="tagId">
            <el-select v-model="queryParams.tagId" placeholder="请选择标签" clearable>
              <el-option
                v-for="item in tagOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
              <el-option v-for="item in statusOptions" :key="item.id" :value="item.value" :label="item.label" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
  
      <!-- 操作按钮区域 -->
      <el-card class="box-card">
        <template #header>
          <div class="card-header">
            <ButtonGroup>
              <el-button
                type="primary"
                icon="Plus"
                @click="handleAdd"
                v-permission="['sys:article:add']"
              >新增文章</el-button>
              <el-button
                type="danger"
                icon="Delete"
                :disabled="selectedIds.length === 0"
                v-permission="['sys:article:delete']"
                @click="handleBatchDelete"
              >批量删除</el-button>
              <el-button
                type="warning"
                icon="Setting"
                v-permission="['sys:article:reptile']"
                @click="reptileDialog.visible = true"
              >爬取文章</el-button>
            </ButtonGroup>
          </div>
        </template>
  
        <!-- 数据表格 -->
        <el-table
          v-loading="loading"
          :data="tableData"
          style="width: 100%"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection"  width="55" align="center" />
          <el-table-column label="封面" align="center">
            <template #default="scope">
              <el-image
                style="width: 120px; height: 80px;border-radius: 10px"
                :src="scope.row.cover"
              />
            </template>
          </el-table-column>
          <el-table-column label="标题" align="center" prop="title" show-overflow-tooltip />
          <el-table-column label="作者" align="center" prop="nickname" show-overflow-tooltip />
          <el-table-column label="分类" align="center" prop="categoryName" width="100" />
          <el-table-column label="标签" align="center" width="200">
            <template #default="scope">
              <el-tag
                v-for="tag in scope.row.tags"
                :key="tag.id"
                class="mx-1"
                size="small"
              >
                {{ tag.name }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column v-permission="['sys:article:updateStatus']" label="发布状态" align="center" prop="status" width="100">
            <template #default="scope">
                <el-switch @change="handleChangeStatus(scope.row)" style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"  
                v-model="scope.row.status" :active-value="1" :inactive-value="0"/>
            </template>
          </el-table-column>
          <el-table-column label="创建时间" align="center" prop="createTime" width="180" />
          <el-table-column label="操作" align="center" width="200" fixed="right">
            <template #default="scope">
              <el-button
                type="primary"
                link
                icon="Edit"
                @click="handleUpdate(scope.row)"
                v-permission="['sys:article:update']"
              >修改</el-button>
              <el-button
                type="danger"
                link
                icon="Delete"
                @click="handleDelete(scope.row)"
                v-permission="['sys:article:delete']"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
  
        <!-- 分页组件 -->
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="queryParams.pageNum"
            v-model:page-size="queryParams.pageSize"
            :page-sizes="[10, 20, 30, 50]"
            :total="total"
            :background="true"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
  
      <!-- 添加或修改对话框 -->
      <el-dialog
        :title="dialog.title"
        v-model="dialog.visible"
        width="1400px"
        top="3vh"
        :close-on-click-modal="false"
      >
        <el-form
          ref="formRef"
          :model="form"
          :rules="rules"
          label-width="100px"
        >
          <el-form-item label="文章标题" prop="title">
            <el-input v-model="form.title" placeholder="请输入文章标题" />
          </el-form-item>
          
          <el-form-item label="文章封面" prop="cover">
            <UploadImage v-model="form.cover" :limit="1"/>
          </el-form-item>

          <el-form-item label="文章简介" prop="summary">
            <el-input
              v-model="form.summary"
              type="textarea"
              :rows="3"
              placeholder="请输入文章简介"
            />
          </el-form-item>

          <el-row :gutter="20" class="mb-20">
            <el-col :span="12">
              <el-form-item label="文章分类" prop="categoryId">
                <el-select v-model="form.categoryId" placeholder="请选择分类">
                  <el-option
                    v-for="item in categoryOptions"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="文章标签" prop="tagIds">
                <el-select
                  v-model="form.tagIds"
                  multiple
                  placeholder="请选择标签"
                >
                  <el-option
                    v-for="item in tagOptions"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20" class="mb-20">
            <el-col :span="8">
              <el-form-item label="阅读方式" prop="readType">
                <el-select v-model="form.readType" placeholder="请选择阅读方式">
                  <el-option label="免费" :value="1" />
                  <el-option label="会员" :value="2" />
                  <el-option label="付费" :value="3" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="文章类型" prop="isOriginal">
                <el-select v-model="form.isOriginal" placeholder="请选择文章类型">
                  <el-option label="原创" :value="1" />
                  <el-option label="转载" :value="0" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="关键词" prop="keywords">
                <el-input v-model="form.keywords" placeholder="请输入关键词" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="转载地址" prop="originalUrl" v-if="form.isOriginal === 0" class="mb-20">
            <el-input v-model="form.originalUrl" placeholder="请输入转载地址" />
          </el-form-item>

          <el-row :gutter="20" class="mb-20">
            <el-col :span="6">
              <el-form-item label="是否置顶" prop="isStick">
                <el-switch style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
                 v-model="form.isStick" :active-value="1" :inactive-value="0"/>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="是否发布" prop="status">
                <el-select v-model="form.status" placeholder="请选择文章状态">
                  <el-option v-for="item in statusOptions" :key="item.id" :value="Number(item.value)" :label="item.label" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="首页轮播" prop="isCarousel">
                <el-switch style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
                 v-model="form.isCarousel" :active-value="1" :inactive-value="0"/>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="是否推荐" prop="isRecommend">
                <el-switch style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
                 v-model="form.isRecommend" :active-value="1" :inactive-value="0"/>
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="文章内容" prop="contentMd" class="mb-20">
            <mavon-editor
              placeholder="输入文章内容..."
              style="height: 500px; width: 100%"
              ref="mdRef"
              v-model="form.contentMd"
              @imgDel="imgDel"
              @imgAdd="imgAdd"
            />
          </el-form-item>
        </el-form>
  
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="cancel">取 消</el-button>
            <el-button type="primary" :loading="submitLoading" @click="submitForm">确 定</el-button>
          </div>
        </template>
      </el-dialog>

      <!-- 爬取文章对话框 -->
      <el-dialog
        title="爬取文章"
        v-model="reptileDialog.visible"
        width="800px"
      >
        <el-form
          ref="reptileFormRef"
          :model="reptileForm"
          :rules="rules"
          label-width="100px"
        >
          <el-form-item label="爬取地址" prop="url">
            <el-input v-model="reptileForm.url" placeholder="请输入爬取地址" />
          </el-form-item>
        </el-form>
      <div style="margin-top: 20px;">
        <el-alert title="暂时只支持Csdn的文章爬取" type="success" :closable="false" />
      </div>

        <template #footer>  
          <div class="dialog-footer">
            <el-button @click="cancel">取 消</el-button>
            <el-button type="primary" :loading="submitLoading" @click="submitReptile">确 定</el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </template>
  
  <script setup lang="ts">
  import { ElMessage, ElMessageBox } from 'element-plus'
  import type { FormInstance, FormRules } from 'element-plus'
  import UploadImage from '@/components/Upload/Image.vue'
  import { getCategoryListApi } from '@/api/article/category'
  import { getTagListApi } from '@/api/article/tag'
  import { getArticleListApi,getDetailApi,deleteArticleApi,
    addArticleApi,updateArticleApi,updateStatusApi,reptileArticleApi } from '@/api/article'
  import { uploadApi } from '@/api/file'
  import { getDictDataByDictTypesApi } from '@/api/system/dict'

  // 模拟数据
  const categoryOptions = ref<any>([])

  const tagOptions = ref<any>([])

  // 查询参数
  const queryParams = reactive({
    pageNum: 1,
    pageSize: 10,
    title: '',
    categoryId: undefined,
    tagId: undefined,
    status: undefined
  })
  
  const loading = ref(false)
  const total = ref(0)
  const tableData = ref([])
  const queryFormRef = ref<FormInstance>()
  const formRef = ref<FormInstance>()
  const mdRef = ref();
  const submitLoading = ref(false)
  
  // 选中项数组
  const selectedIds = ref<string[]>([])
  
  // 弹窗控制
  const dialog = reactive({
    title: '',
    visible: false,
    type: 'add'
  })

  const reptileDialog = reactive({
    visible: false,
  })
  
  // 表单数据
  const form = reactive({
    id: undefined,
    title: '',
    cover: '',
    summary: '',
    categoryId: undefined,
    tagIds: [],
    content: '',
    contentMd: '',
    readType: 0,
    isOriginal: 1,
    originalUrl: '',
    isStick: 0,
    status: 1,
    isCarousel: 0,
    isRecommend: 0,
    keywords: ''
  })

  const reptileForm = reactive({
    url: ''
  })

  const statusOptions = ref<any>([])
  
  // 表单校验规则
  const rules = reactive<FormRules>({
    title: [
      { required: true, message: '请输入文章标题', trigger: 'blur' },
      { min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur' }
    ],
    categoryId: [
      { required: true, message: '请选择文章分类', trigger: 'change' }
    ],
    contentMd: [
      { required: true, message: '请输入文章内容', trigger: 'blur' }
    ],
    summary: [
      { required: true, message: '请输入文章简介', trigger: 'blur' },
      { max: 500, message: '简介最多500个字符', trigger: 'blur' }
    ],
    readType: [
      { required: true, message: '请选择阅读方式', trigger: 'change' }
    ],
    isOriginal: [
      { required: true, message: '请选择文章类型', trigger: 'change' }
    ],
    tagIds: [
      { required: true, message: '请选择文章标签', trigger: 'change' }
    ],
    originalUrl: [
      { 
        required: true, 
        message: '请输入转载地址', 
        trigger: 'blur',
        validator: (rule: any, value: string, callback: any) => {
          if (form.isOriginal === 0 && !value) {
            callback(new Error('转载文章必须填写转载地址'))
          } else {
            callback()
          }
        }
      }
    ]
  })

    //添加图片
    function imgDel(pos: any, $file: any) {

    }
    //添加图片
    function imgAdd(pos: any, $file: any) {
    var formdata = new FormData();
    formdata.append("file", $file);
    uploadApi(formdata).then((res) => {
        mdRef.value.$img2Url(pos, res.data);
    });
    }
 
  // 获取分类列表
  const getList = async () => {
    loading.value = true
    try {
      const { data } = await getArticleListApi(queryParams)
      tableData.value = data.records
      total.value = data.total
    } catch (error) {
    }
    loading.value = false
  }

  // 获取状态列表
  const getStatusList = async () => {
    const { data } = await getDictDataByDictTypesApi('article_status')
    statusOptions.value = data.article_status.list
  }
  
  // 表格选择项变化
  const handleSelectionChange = (selection: any[]) => {
    selectedIds.value = selection.map(item => item.id)
  }

  // 爬取文章
  const submitReptile = () => {
    if (!reptileForm.url) return
    reptileArticleApi(reptileForm.url).then((res) => {
      ElMessage.success('爬取成功')
      getList()
      reptileDialog.visible = false
      reptileForm.url = ''
    })
  }
  
  // 批量删除
  const handleBatchDelete = () => {
    if (selectedIds.value.length === 0) return
    
    ElMessageBox.confirm(`是否确认删除 ${selectedIds.value.length} 篇文章?`, '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(async () => {
      try {
        await deleteArticleApi(selectedIds.value)
        ElMessage.success('删除成功')
        selectedIds.value = []
        getList()
      } catch (error) {
      }
    })
  }

  // 删除
  const handleDelete = (row: any) => {
    ElMessageBox.confirm(`是否确认删除 ${row.title} 这篇文章?`, '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(async () => {
      try {
        await deleteArticleApi(row.id)
        ElMessage.success('删除成功')
        getList()
      } catch (error) {
      }
    })
  }

  // 发布文章
  const handleChangeStatus = (row: any) => {
    updateStatusApi({id: row.id, status: row.status}).then((res) => {
      ElMessage.success('修改成功')
      getList()
    })
  }
  
  // 搜索
  const handleQuery = () => {
    queryParams.pageNum = 1
    getList()
  }
  
  // 重置查询
  const resetQuery = () => {
    queryFormRef.value?.resetFields()
    handleQuery()
  }

  //清空表单
  const clearForm = () => {
    form.id = undefined
    form.title = ''
    form.cover = ''
    form.summary = ''
    form.categoryId = undefined
    form.tagIds = []
    form.content = ''
    form.contentMd = ''
  }
  
  // 新增用户
  const handleAdd = () => {
    dialog.type = 'add'
    dialog.title = '新增文章'
    dialog.visible = true
    clearForm()
  }
  
  // 修改分类
  const handleUpdate = (row: any) => {
    clearForm()
    dialog.type = 'edit'
    dialog.title = '修改文章'
    dialog.visible = true
    getDetailApi(row.id).then((res) => {
      Object.assign(form, res.data)
    })
  }
  
  // 提交表单
  const submitForm = async () => {
    if (!formRef.value) return
    
    await formRef.value.validate(async (valid) => {
      if (valid) {
        submitLoading.value = true
        form.content = mdRef.value.d_render;
        try {
          if (dialog.type === 'add') {
            await addArticleApi(form)
            ElMessage.success('新增成功')
          } else {
            await updateArticleApi(form)
            ElMessage.success('修改成功')
          }
          getList()
          dialog.visible = false
        } catch (error) {
        } finally {
          submitLoading.value = false
        }
      }
    })
  }
  
  // 取消按钮
  const cancel = () => {
    dialog.visible = false
    reptileDialog.visible = false
    formRef.value?.resetFields()
    reptileForm.url = ''
  }
  
  // 分页大小改变
  const handleSizeChange = (val: number) => {
    queryParams.pageSize = val
    getList()
  }
  
  // 页码改变
  const handleCurrentChange = (val: number) => {
    queryParams.pageNum = val
    getList()
  }
  
  // 初始化
  onMounted(() => {
    getList()
    getCategoryListApi({pageNum: 1, pageSize: 1000}).then((res) => {
      categoryOptions.value = res.data.records
    })
    getTagListApi({pageNum: 1, pageSize: 1000}).then((res) => {
      tagOptions.value = res.data.records
    })

    getStatusList()
  })
  
  // 图片上传前的处理
  const beforeAvatarUpload = (file: File) => {
    // 这里添加文件类型和大小限制
    const isJPG = file.type === 'image/jpeg'
    const isPNG = file.type === 'image/png'
    const isLt2M = file.size / 1024 / 1024 < 2

    if (!isJPG && !isPNG) {
      ElMessage.error('上传头像图片只能是 JPG/PNG 格式!')
      return false
    }
    if (!isLt2M) {
      ElMessage.error('上传头像图片大小不能超过 2MB!')
      return false
    }
    
    // 模拟上传
    form.cover = URL.createObjectURL(file)
    return false
  }
  </script>
  
  <style lang="scss" scoped>
    .avatar-uploader {
        :deep(.el-upload) {
            border: 2px dashed var(--el-border-color-lighter);
            border-radius: 8px;
            cursor: pointer;
            position: relative;
            overflow: hidden;
            transition: var(--el-transition-duration-fast);
    
            &:hover {
            border-color: var(--el-color-primary);
            background-color: var(--el-color-primary-light-9);
        }
      }
  
      .avatar-uploader-icon {
        font-size: 28px;
        color: var(--el-text-color-secondary);
        width: 120px;
        height: 120px;
        text-align: center;
        line-height: 120px;
      }
  
      .avatar {
        width: 120px !important;
        height: 120px !important;
      }
    }
  .app-container {

    .pagination-container {
      display: flex;
      justify-content: center;
      margin-top: 20px;
    }
  
    :deep(.el-dialog) {
      .el-dialog__body {
        padding: 20px 40px;
      }
  
      .el-form {
        .el-form-item {
          margin-bottom: 22px;
          
          &:last-child {
            margin-bottom: 0;
          }
  
          .el-form-item__label {
            font-weight: 500;
            padding-right: 20px;
          }
        }
  
        .el-select {
          width: 100%;
        }
      }
  
      .v-note-wrapper {
        z-index: 1;
        min-height: 500px;
        margin-bottom: 20px;
      }
    }

    .mb-20 {
      margin-bottom: 20px;
    }
  
  
  
    .dialog-footer {
      text-align: right;
      padding-top: 20px;
      border-top: 1px solid var(--el-border-color-lighter);
      
      .el-button {
        padding: 12px 25px;
        
        & + .el-button {
          margin-left: 12px;
        }
      }
    }
  
    .el-tag {
      margin-right: 8px;
      margin-bottom: 8px;
    }
  }
  
  :root[data-theme='dark'] {
    .app-container {
      :deep(.el-dialog) {
        .el-form {
          .el-input__wrapper {
            box-shadow: 0 0 0 1px var(--el-border-color) inset;
          }
        }
      }
    }
  }
  </style> 